package cn.wolfcode.crm.shiro;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionsHandler {

    @ExceptionHandler(UnauthorizedException.class)
//    第一个参数表示当前请求中抛出的异常
    public void exceptionHandler(HandlerMethod method, HttpServletResponse response)throws IOException
    {
        /*由于请求分普通请求和ajax请求两种，一般请求和ajax请求此处只有@ResponseBody注解这个区别*/
        ResponseBody annotation = method.getMethodAnnotation(ResponseBody.class);
//        不为空则是ajax请求
        if(annotation != null)
        {
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().println("{\"success\":false,\"msg\":\"没有执行当前操作的权限\"}");
        }
        else
        {
            response.setContentType("text/html;charset=utf-8");
            response.sendRedirect("/nopermission.jsp");
        }
    }
}
